<?php

namespace Lib;

use EasySwoole\Component\Di;

class RedisManager
{
    public static function init(): \Redis
    {
        $redis = Di::getInstance()->get('redis');
        if ($redis === null) {
            $redis = self::connectRedis(new \Redis());
            Di::getInstance()->set('redis', $redis);
        }
        try {
            $ping = $redis->ping();
        } catch (\Exception $e) {
            self::connectRedis($redis);
            $ping = true;
        }
        if (!$ping) {
            self::connectRedis($redis);
        }
        return $redis;
    }

    private static function connectRedis($redis)
    {
        $redis->connect(config('env.REDIS_HOST'), config('env.REDIS_PORT'));
        $redis->auth(config('env.REDIS_PASSWORD'));
        return $redis;
    }
}
